package org.auth.config;

import javax.sql.DataSource;

import org.auth.framework.CustomUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

@Configuration
public class OAuth2ServerConfig extends AuthorizationServerConfigurerAdapter {
	/**
	 * DB数据源
	 */
	@Autowired
	private DataSource dataSource;
	
	/**
	 * Redis数据源
	 */
	@Autowired
	private RedisConnectionFactory redisConnection;
	
	/**
	 * authenticationManager
	 */
	@Autowired
	private AuthenticationManager authenticationManager;
	
	/**
	 * 自定义UserDetailsService对象
	 */
	@Autowired
	private CustomUserDetailsService customUserDetailsService;

	/**
	 * OAuth对外开放
	 * 
	 * @param oauthServer 服务
	 */
	@Override
	public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
		oauthServer.tokenKeyAccess("permitAll()")
				.checkTokenAccess("isAuthenticated()")
				.allowFormAuthenticationForClients();
	}

	/**
	 * 设定TOken存储方式->Redis
	 * 
	 * @return TOken存储方式
	 */
	@Bean
	public TokenStore tokenStore() {
		return new RedisTokenStore(redisConnection);
	}

	/**
	 * 设定TOken存储方式->Redis
	 * 
	 * @param endpoints 认证配置
	 */
	@Override
	public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
		endpoints.authenticationManager(authenticationManager).tokenStore(tokenStore())
				.userDetailsService(customUserDetailsService);
	}

	/**
	 * Oauth的Client信息的存储方式->DB
	 * 
	 * @param Client设定对象
	 */
	@Override
	public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
		clients.jdbc(dataSource);

	}
}
